package cn.king.pet.service.impl;

import cn.king.basic.dto.MsgDto;
import cn.king.basic.exception.BusinessException;
import cn.king.basic.service.IBaiduAiAuditService;
import cn.king.basic.util.*;
import cn.king.order.domain.OrderPetAcquisition;
import cn.king.order.mapper.OrderPetAcquisitionMapper;
import cn.king.org.domain.Employee;
import cn.king.org.domain.Shop;
import cn.king.org.mapper.EmployeeMapper;
import cn.king.org.mapper.ShopMapper;
import cn.king.pet.domain.SearchMasterMsg;
import cn.king.pet.domain.SearchMasterMsgAuditLog;
import cn.king.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.king.pet.mapper.SearchMasterMsgMapper;
import cn.king.pet.query.SearchMasterMsgQuery;
import cn.king.pet.service.ISearchMasterMsgService;
import cn.king.basic.service.impl.BaseServiceImpl;
import cn.king.user.domain.Logininfo;
import cn.king.user.domain.User;
import cn.king.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.getByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.add(msg);

        //百度ai智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        if (boo1 && boo2){ //审核通过
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核成功！");
            searchMasterMsgAuditLogMapper.add(log);

            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.getAll());
            if(nearestShop != null){ //找到最近的店铺
                msg.setShopId(nearestShop.getId());
                //给店铺发送消息 [没有短信次数，暂时使用idea控制台打印]
                //SmsUtils.sendSms(nearestShop.getTel(),"你有新的订单，请尽快处理！");
                System.out.println("你有新的订单，请尽快处理！");
            }else { //50公里内，没有找到店铺
                //放到寻主池
                msg.setState(3);
                //给用户发送短信
                //SmsUtils.sendSms(nearestShop.getTel(),"你附近暂时没有店铺，请敬请期待！");
                System.out.println("你附近暂时没有店铺，请敬请期待！");
            }
            searchMasterMsgMapper.update(msg);
            return new AjaxResult();
        }else { //审核不通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败！");
            searchMasterMsgAuditLogMapper.add(log);

            //SmsUtils.sendSms(nearestShop.getTel(),"你附近暂时没有店铺，请敬请期待！");
            System.out.println("寻主消息发布失败，请修改之后重新发布！");
            //删除寻主消息
            searchMasterMsgMapper.delete(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息发布失败，请修改之后重新发布！");
        }
    }

    /**
     * 查询用户的寻主消息
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息，设置User_id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.getByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询已完成寻主的消息
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.getByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){ //店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询寻主池的寻主消息
        query.setState(3);
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理的寻主消息
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.getByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){ //店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        //拒单：寻主消息已经分配给某一个店铺，店铺拒单了
        //拒单之后，放入寻主池 - state=3，置空店铺id
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(MsgDto msgDto) {
        //平台将寻主消息分给店铺，店铺接收，派人接宠物
        //判断订单是否存在
        OrderPetAcquisition order = orderPetAcquisitionMapper.getByMsgId(msgDto.getMsgId());
        if (order != null && order.getState() == 0){
            throw new BusinessException("订单正在处理，请勿重复接单！！！");
        }
        //生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.getOne(msgDto.getMsgId());
        OrderPetAcquisition newOrder = createOrder(msg,msgDto);
        orderPetAcquisitionMapper.add(newOrder);
        //告诉处理人在规定时间内处理订单
        //Employee employee = employeeMapper.getById(msgDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在两天内到"+msg.getAddress()+"接回宠物！");
        System.out.println("你有新的订单，请在两天内到"+msg.getAddress()+"接回宠物！");
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        //最后确认时间
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
//        order.setPaytype(); //没有，接宠物的时候才会有
//        order.setState(); //实体类默认值待处理 - 0
//        order.setPetId(); //没有，宠物接回来后才有
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
